/**
 * ...
 * @author Thot
 */

function EditorModel(){}

EditorModel._instance = null;
EditorModel.getInstance = function()
{
	if( EditorModel._instance == null )
		EditorModel._instance = new EditorModel();
		
	return EditorModel._instance;
};

EditorModel.prototype.autoSave = true;
EditorModel.prototype.autoSaveTime = 10000;
EditorModel.prototype.portraitWidth = 100;
EditorModel.prototype.portraitHeight = 80;
EditorModel.prototype.portraitId = 1000;
EditorModel.prototype.landscapeId = 2000;
EditorModel.prototype.ficheId = -1;
EditorModel.prototype.saveURLFiche = "";
EditorModel.prototype.saveURLImage = "";
EditorModel.prototype.assetsPath = "";
EditorModel.prototype.uiPath = "";

EditorModel.prototype._uiTextures = [
	{url:'picker.png',name:'picker'},
	{url:'cross.png',name:'cross'},
	{url:'resize.png',name:'resize'},
	{url:'rotation.png',name:'rotation'},
	{url:'up.png',name:'up'},
	{url:'DPE_0.png',name:'dpe'},
	{url:'GES_0.png',name:'ges'},
];

EditorModel.prototype._container = null;
EditorModel.prototype._addBackgroundButton = null;
EditorModel.prototype._addTextButton = null;
EditorModel.prototype._addImageButton = null;
EditorModel.prototype._addDPEButton = null;
EditorModel.prototype._addGESButton = null;
EditorModel.prototype._rentButton = null;
EditorModel.prototype._sellButton = null;
EditorModel.prototype._portraitButton = null;
EditorModel.prototype._landscapeButton = null;
EditorModel.prototype._titeField = null;
EditorModel.prototype._themeField = null;
EditorModel.prototype._formatField = null;
EditorModel.prototype._saveButton = null;
EditorModel.prototype._textEditor = null;
EditorModel.prototype._time = 0;
EditorModel.prototype._data = null;
EditorModel.prototype._fileReader = null;
EditorModel.prototype._textureManager = null;
EditorModel.prototype._ratio = 1;
EditorModel.prototype._numFiles = 0;
EditorModel.prototype._totalRequest = 0;

//public init
EditorModel.prototype.init = function(data)
{
	this._data = data;
	this._initCanvas();
	this._textEditor = new TextEditor();
	this._textEditor.init("texteditor");
	this._elementEditor = new ElementEditor();
	this._elementEditor.init();
	this._initListeners();
	this._initAssets();
	this.setLoaderVisible(false);
	this.changeOrientation();
};

EditorModel.prototype._appReady = function()
{
	var loader = tomahawk_ns.AssetsLoader.getInstance();
	var data = loader.getData();
	var tex = null;
	
	for( var prop in data )
	{
		tex = new tomahawk_ns.Texture();
		tex.name = prop;
		tex.data = data[prop];
		tex.rect = [0,0,data[prop].width,data[prop].height];
		
		tomahawk_ns.AssetsManager.getInstance().addTexture(tex,tex.name);
	}
		
	this._loadData(this._data);
	tomahawk_ns.Stage.getInstance().addEventListener( tomahawk_ns.Event.ENTER_FRAME, this, this._enterFrame );
};

EditorModel.prototype._progressHandler = function(event)
{
	var loader = event.target;
};

EditorModel.prototype._initAssets = function()
{
	var usedTextures = this._getUsedTextures();
	var loader = tomahawk_ns.AssetsLoader.getInstance();
	var i = usedTextures.length;
	var obj = null;
	
	loader.addEventListener( tomahawk_ns.Event.COMPLETE, this, this._appReady );
	loader.addEventListener( tomahawk_ns.Event.PROGRESS, this, this._progressHandler );
	
	while( --i > -1 )
	{
		loader.addFile(this.assetsPath + usedTextures[i], usedTextures[i]);
		this._numFiles++;
	}
	
	i = this._uiTextures.length;
	
	while( --i > -1 )
	{
		obj = this._uiTextures[i];
		loader.addFile( this.uiPath + obj.url, obj.name );
		this._numFiles++;
	}
	
	loader.load();
};

EditorModel.prototype.changeOrientation = function(event)
{
	var DOMEditor = document.getElementById("editorZone");
	var ratio = this.portraitWidth / this.portraitHeight;
	var background = this._container.getChildByName("ficheBackground");
	var canvas = document.getElementById("canvasEditor"); 
	var value = ( this._portraitButton.checked ) ? this.portraitId : this.landscapeId;
	
	if( background == null )
		background = new tomahawk_ns.Shape();
		
	//landscape
	if( value == this.portraitId )
	{
		ratio = this.portraitWidth / this.portraitHeight;
		canvas.width = AppConstants.BASE_SIZE;
		canvas.height = canvas.width / ratio;
	}
	else
	{
		canvas.height = AppConstants.BASE_SIZE;
		canvas.width = canvas.height / ratio;
	}
	
	canvas.style.marginTop = parseInt(( DOMEditor.offsetHeight - canvas.height ) * 0.5)+'px';
	canvas.style.marginLeft = parseInt(( DOMEditor.offsetWidth - canvas.width ) * 0.5)+'px';
	
	// plain background
	background.name = "ficheBackground";
	background.beginPath();
	background.fillStyle("white");
	background.fillRect(0,0,100,100);
	background.fill();
	background.width = 100;
	background.height = 100;
	background.scaleX = canvas.width / background.width;
	background.scaleY = canvas.height / background.height;
	background.cacheAsBitmap = true;
	
	//set mouseEnabled to true
	background.mouseEnabled = true;
	
	tomahawk_ns.Stage.getInstance().addChildAt(background,0);
};

EditorModel.prototype._initCanvas = function()
{
	var canvas = document.getElementById("canvasEditor"); 
	this._container = new tomahawk_ns.Sprite();
	this._container.mouseEnabled = true;
	
	// init tomahawk
	tomahawk_ns.Stage.getInstance().init(canvas);
	tomahawk_ns.Stage.getInstance().addChild(this._container);
};

EditorModel.prototype._loadData = function()
{
	var data = this._data;
	var container = this._container;
	var dataChild = null;
	var child = null;
	var i = 0;
	var max = data.length;

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];
		
		if( dataChild.type == "TransformableBitmap" )
			child = new TransformableBitmap();
		
		if( dataChild.type == "MesureComponent" )
			child = new MesureComponent();
		
		if( dataChild.type == "TransformableText" )
			child = new TransformableText();
		
		if( child == null )
			continue;
			
		child.unserialize(dataChild);
		container.addChild(child);
	}
};



//private
EditorModel.prototype._getUsedTextures = function()
{
	var data = this._data;
	var container = this._container;
	var dataChild = null;
	var i = 0;
	var max = data.length;
	var results = new Array();

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];

		if( dataChild.type == "TransformableBitmap" && dataChild.textureName != null)
		{
			results.push(dataChild.textureName);
		}
	}
	
	return results;
};

EditorModel.prototype._enterFrame = function(event)
{
	var curTime = new Date().getTime();
	if( curTime - this._time > this.autoSaveTime )
	{
		if( this.autoSave == true )
			this.save();
			
		this._time = curTime;
	}
	//tomahawk_ns.Stage.getInstance().drawFPS();
};

EditorModel.prototype._focusHandler = function(event)
{
	if( event.type == tomahawk_ns.Event.FOCUSED || event.type == tomahawk_ns.Event.UNFOCUSED )
	{
		var target = ( event.type == tomahawk_ns.Event.FOCUSED ) ? event.target : null;
		this._textEditor.setCurrentTextField(target);
	}
	
	if( event.type == EditorEvent.SELECT_OBJECT || event.type == EditorEvent.UNSELECT_OBJECT )
	{
		var target = ( event.type == EditorEvent.SELECT_OBJECT ) ? event.target : null;
		if( target != null )
			this._elementEditor.setCurrentElement(target);
	}
};

EditorModel.prototype._initListeners = function()
{
	var scope = this;
	var callback1 = function(){scope._mouseHandler.apply(scope,arguments);};
	var callback2 = function(){scope.save.apply(scope,arguments);};
	var callback3 = function(){scope.changeOrientation();};
	
	this._addBackgroundButton = document.getElementById('addBackgroundImage');
	this._addImageButton = document.getElementById('addImage');
	this._addDPEButton = document.getElementById('addDPE');
	this._addGESButton = document.getElementById('addGES');
	this._addTextButton = document.getElementById('addText');
	this._rentButton = document.getElementById('rentButton');
	this._sellButton = document.getElementById('sellButton');
	this._saveButton = document.getElementById('save');
	this._titeField = document.getElementById('ficheTitle');
	this._goodTypeField = document.getElementById('goodType');
	this._rentField = document.getElementById('rent');
	this._publicField = document.getElementById('public');
	this._themeField = document.getElementById('ficheTheme');
	this._formatField = document.getElementById('ficheFormat');
	this._portraitButton = document.getElementById('portraitBtn');
	this._landscapeButton = document.getElementById('landscapeBtn');
	this._addPrice = document.getElementById('addPrice');
	this._addTitle = document.getElementById('addTitle');
	this._addDetails = document.getElementById('addDetails');
	this._addHook = document.getElementById('addHook');
	
	this._container.addEventListener(tomahawk_ns.Event.FOCUSED, this, this._focusHandler,true);
	this._container.addEventListener(tomahawk_ns.Event.UNFOCUSED, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.SELECT_OBJECT, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.UNSELECT_OBJECT, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.USER_IMAGE_ADDED, this, this._addUserImageHandler,true);
	
	this._addHook.onclick = callback1;
	this._addDetails.onclick = callback1;
	this._addPrice.onclick = callback1;
	this._addTitle.onclick = callback1;
	this._addBackgroundButton.onclick = callback1;
	this._addTextButton.onclick = callback1;
	this._addImageButton.onclick = callback1;
	this._addDPEButton.onclick = callback1;
	this._addGESButton.onclick = callback1;
	this._rentButton.onclick = callback1;
	this._sellButton.onclick = callback1;
	this._saveButton.onclick = callback2; // save
	this._portraitButton.onclick = callback3;
	this._landscapeButton.onclick = callback3;
};

EditorModel.prototype._mouseHandler = function(event)
{
	//centre, par défaut, sélectionné
	var child = null;
	var container = EditorModel.getInstance()._container;
	var stage  = tomahawk_ns.Stage.getInstance();
	var texture = null;
	var format = new tomahawk_ns.TextFormat();
	
	if( event.target == this._addHook )
	{
		format.size = 20;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(300,150,150,50);
		child.setText(Localization.getInstance().getLabel("ACCROCHE"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "hook";
	}
	
	if( event.target == this._addImageButton )
	{
		child = new TransformableBitmap();
	}
	
	if( event.target == this._addTitle )
	{
		format.size = 30;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(0,0,150,50);
		child.setText(Localization.getInstance().getLabel("TITRE"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "title";
	}		
	
	if( event.target == this._addDetails )
	{
		format.size = 12;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(100,100,150,50);
		child.setText(Localization.getInstance().getLabel("DETAILS"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "details";
	}	
	
	if( event.target == this._addPrice )
	{
		format.size = 20;
		format.textColor = "black";
		child = new TransformableText(format);
		child.init(300,20,150,50);
		child.setText(Localization.getInstance().getLabel("PRIX"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.background = true;
		child.backgroundColor = "white";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "price";
	}
	
	if( event.target == this._addBackgroundButton )
	{
		child = container.getChildByName("background");
		if( child != null )
		{
			container.removeChild(child);
		}
		
		child = new TransformableBitmap();
		child.name = "background";
		child.resize(stage.getCanvas().width,stage.getCanvas().height);
	}
	
	if( event.target == this._addDPEButton )
	{
		//child = new TransformableBitmap();
		child = new MesureComponent();
		child.name = "dpe";
		texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias('dpe');
		child.resize( 200, 100 );
		child.setTexture(texture);
		child.resizeByWidth();
		child.range = MesureComponent.RANGE_DPE;
	}
	
	if( event.target == this._addGESButton )
	{
		child = new MesureComponent();
		child.name = "ges";
		texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias('ges');
		child.resize( 200, 100 );
		child.setTexture(texture);
		child.resizeByWidth();
		child.range = MesureComponent.RANGE_GES;
	}

	if( event.target == this._addTextButton )
	{
		child = new TransformableText();
		child.init(50,50,100,100);
		child.setText(Localization.getInstance().getLabel("VOTRE_TEXTE_ICI"));
		child.autoFocus();
		child.padding = 15;
	}	
	
	if( event.target == this._rentButton )
	{
		format.size = 30;
		format.textColor = "white";
		child = new TransformableText(format);
		child.init(200,200,150,50);
		child.setText(Localization.getInstance().getLabel("LOUE"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.rotation = -45;
		child.background = true;
		child.backgroundColor = "red";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "rent";
	}	
	
	if( event.target == this._sellButton )
	{
		format.size = 30;
		format.textColor = "white";
		child = new TransformableText(format);
		child.init(200,200,150,50);
		child.setText(Localization.getInstance().getLabel("VENDU"));
		child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
		child.padding = 15;
		child.rotation = -45;
		child.background = true;
		child.backgroundColor = "red";
		child.border = true;
		child.borderColor = "black";
		child.resize(150,50);
		child.autoFocus();
		child.name = "sell";
	}
	
	if( child != null )
	{
		if( child.name == "background" )
		{
			container.addChildAt( child, 0 );
		}
		else
		{
			container.addChild( child );
		}
	}
	
	event.target.blur();
	stage.getCanvas().focus();
};


EditorModel.prototype.setLoaderVisible = function(value)
{
	if( value == true )
	{
		document.getElementById('loaderImg').style.visibility = 'visible';
	}
	else
	{
		document.getElementById('loaderImg').style.visibility = 'hidden';
	}
};



EditorModel.prototype._addUserImageHandler = function(event)
{
	var data = event.data.data;
	var fileName = event.data.name;
	this.setLoaderVisible(true);
	this._totalRequest++;
	
	ImageFileSaver.onComplete = this._saveComplete.bind(this);
	ImageFileSaver.save(this.saveURLImage+"&ficheId="+this.ficheId,data,fileName);
};

EditorModel.prototype._saveComplete = function()
{
	this._totalRequest = ( this._totalRequest - 1 <  0 ) ? 0 : this._totalRequest - 1;
	this.setLoaderVisible(this._totalRequest > 0);
};

//save fiche data
EditorModel.prototype.save = function()
{
	var orientation = ( this._portraitButton.checked ) ? this._portraitButton.value : this._landscapeButton.value;
	var url = this.saveURLFiche+"&ficheId="+this.ficheId;
	var child = null;
	var i = 0;
	var max = this._container.children.length;
	var save = new Array();
	var stage = tomahawk_ns.Stage.getInstance();
	var ratio = 150 / stage.getCanvas().width;
	var preview = document.createElement("canvas");
	var context = preview.getContext("2d");
	var str = null;
	
	
	for( i = 0; i < max; i++ )
	{
		child = this._container.children[i];
		save.push(child.serialize());
	}
	
	
	preview.width = 150;
	preview.height = 107;
	context.scale(ratio,ratio);
	context.drawImage(stage.getCanvas(),0,0);
	
	
	str = JSON.stringify(save);
	
	url += "&ficheName="+this._titeField.value;
	url += "&ficheTheme="+this._themeField.value;
	url += "&ficheFormat="+this._formatField.value;
	url += "&goodType="+this._goodTypeField.value;
	url += "&rent="+this._rentField.value;
	url += "&public="+this._publicField.value;
	url += "&orientation="+orientation;
	
	this.setLoaderVisible(true);
	this._totalRequest++;
	
	FicheSaver.onComplete = this._saveComplete.bind(this);
	FicheSaver.save(url,str,preview.toDataURL());
};






